import { _decorator, Color, color, Component, math, Node, random, Sprite, v2, Vec2, Vec3 } from 'cc';
import { PoolManager } from './PoolManager';
import { MoveItemManager } from './MoveItemManager';
const { ccclass, property } = _decorator;

@ccclass('MoveItem')
export class MoveItem extends Component {

    @property(Sprite)
    public Icon: Sprite = null;

    private _lifetime: number;
    private _invincibleTime: number;
    private _speed: number;
    private _timer: number = 0;
    private _offset: number = 10;
    private _velocity: Vec2 = Vec2.ZERO;

    init(parent: Node, worldPos: Vec3, lifetime: number, invincibleTime: number, speed: number) {
        this.node.setParent(parent);
        this.node.setWorldPosition(this.getOffsetPos(worldPos.clone()));
        this._lifetime = lifetime;
        this._invincibleTime = invincibleTime;
        this._speed = speed;
        this._timer = 0;
        this.Icon.color = this.getRandomColor();

        // 1. 随机角度
        let angle = Math.random() * 2 * Math.PI;

        // 2. 方向向量
        let dir = v2(Math.cos(angle), Math.sin(angle));
        // 3. 设置速度向量
        this._velocity = dir.multiplyScalar(speed);
    }

    protected update(dt: number): void {
        this._timer += dt;
        this.node.setWorldPosition(this.node.getWorldPosition().add3f(this._velocity.x * dt, this._velocity.y * dt, 0));

        if (this._timer > this._lifetime) {
            PoolManager.Instance.put(this.node);
        }

        if (this._timer > this._invincibleTime && MoveItemManager.Instance.getDis(this.node) < 90) {
            PoolManager.Instance.put(this.node);
            MoveItemManager.Instance.createItems(3);
            MoveItemManager.Instance.addScore();
        }
    }

    // 生成一个随机的 cc.Color
    getRandomColor(): Color {
        let r = Math.floor(Math.random() * 256);
        let g = Math.floor(Math.random() * 256);
        let b = Math.floor(Math.random() * 256);
        return new Color(r, g, b, 255);
    }

    getOffsetPos(pos: Vec3) {
        return pos.add3f(math.randomRange(-this._offset, this._offset), math.randomRange(-this._offset, this._offset), 0);
    }
}


